import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/pages/main/market/market_controller.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_collection_detail/market_collection_detail_page.dart';

import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/empty_widget.dart';

class MarketPage extends StatefulWidget {
  static String path = '/MarketPage';
  const MarketPage({super.key});

  @override
  State<StatefulWidget> createState() => _MarketPageStates();
}

class _MarketPageStates extends State<MarketPage> {
  final ScrollController scrollController = ScrollController();

  final MarketController controller = Get.put(MarketController());
  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        controller.getListData(loadMore: true);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
          Obx(
            () => Container(
              padding: EdgeInsets.zero,
              color: Colors.transparent,
              child: RefreshIndicator(
                backgroundColor: Colors.transparent,

                // ignore: sort_child_properties_last
                child: CustomScrollView(
                  controller: scrollController,
                  physics: AlwaysScrollableScrollPhysics(),
                  slivers: [
                    SliverToBoxAdapter(
                      child: Column(
                        children: [
                          Container(
                            width: 375.px,
                            padding: EdgeInsets.only(top: top),
                            decoration: BoxDecoration(
                              // color: AppColors.backgroundColorBlack,
                              color: Colors.transparent,
                            ),
                            child: Stack(
                              children: [
                                Center(
                                  child: Column(
                                    children: [
                                      ImageAssetWidget(
                                        imageUrl: 'static/images/market/fh.png',
                                        width: 120.px,
                                        height: 44.px,
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Obx(() {
                            return controller.listMarketTime.value != null
                                ? _topTab(
                                  context: context,
                                  startTime:
                                      '${controller.listMarketTime.value?.saleStartTime}-${controller.listMarketTime.value?.saleEndTime}',
                                  endTime:
                                      '${controller.listMarketTime.value?.buyStartTime}-${controller.listMarketTime.value?.buyEndTime}',
                                )
                                : SizedBox(width: 100.px, height: 100.px);
                          }),
                        ],
                      ),
                    ),
                    if (controller.listMarket.isEmpty)
                      const SliverToBoxAdapter(child: EmptyWidget()),

                    // SliverPadding(
                    //   padding: EdgeInsets.fromLTRB(12.px, 0.px, 12.px, 0.px),
                    //   sliver: SliverList(
                    //     delegate: SliverChildBuilderDelegate(
                    //       childCount: controller.listMarket.length,
                    //       (BuildContext context, int index) {
                    //         return _buildItem(context, index);
                    //       },
                    //     ),
                    //   ),
                    // ),
                    SliverPadding(
                      padding: EdgeInsets.fromLTRB(12.px, 10.px, 12.px, 50.px),
                      sliver: SliverGrid(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          crossAxisSpacing: 10.px,
                          mainAxisSpacing: 12.px,
                          childAspectRatio: 169.px / 243.px,
                        ),
                        delegate: SliverChildBuilderDelegate(
                          childCount: controller.listMarket.length,
                          (BuildContext context, int index) {
                            return LayoutBuilder(
                              builder: (
                                BuildContext context,
                                BoxConstraints constraints,
                              ) {
                                return _buildItem(context, index);
                              },
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
                onRefresh: _handleRefresh,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _handleRefresh() async {
    controller.getListData();
    controller.getTime();
    return;
  }

  Widget _topTab({
    required BuildContext context,
    String startTime = '暂未开放',
    String endTime = '暂未开放',
  }) {
    return Container(
      width: context.width,
      height: 38.px,
      padding: EdgeInsets.fromLTRB(13.px, 0, 13.px, 0),
      // decoration: BoxDecoration(color: AppColors.backgroundColorGrey2),
      color: Colors.transparent,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '挂单时间:$startTime',
            style: TextStyle(fontSize: 11, color: AppColors.backgroundColor),
          ),
          Text(
            '购买时间:$endTime',
            style: TextStyle(fontSize: 11, color: AppColors.backgroundColor),
          ),
        ],
      ),
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    final item = controller.listMarket[index];
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          '${MarketCollectionDetailPage.path}?id=${item.collectionId}',
          arguments: {'id': item.collectionId},
        );
      },
      child: Stack(
        children: [
          Container(
            // margin: EdgeInsets.only(bottom: 12.px),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.px),
              // border: Border.all(color: AppColors.backgroundColor,width: 1.px),
              // color: AppColors.backgroundColorBlack,
              color: Color.fromRGBO(31, 33, 38, 1),
            ),
            child: Column(
              children: [
                SizedBox(
                  width: context.width,
                  height: 174.px,
                  child: LazyImage(
                    imageUrl: '${item.coverImageUrl}',
                    height: 174.px,
                    width: context.width,
                    boxFit: BoxFit.cover,
                    borderRadius: 8.px,
                  ),
                ),
                SizedBox(height: 12),
                Padding(
                  padding: EdgeInsets.only(left: 12.px, right: 12.px),
                  child: SizedBox(
                    width: context.width,
                    child: Text(
                      '${item.collectionName}',
                      style: TextStyle(
                        color: AppColors.fontColor,
                        fontSize: 12.px,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
                SizedBox(height: 4),
                Padding(
                  padding: EdgeInsets.only(left: 12.px, right: 12.px),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '￥',
                            style: TextStyle(
                              fontSize: 14.px,
                              color: AppColors.startColor,
                            ),
                          ),
                          Text(
                            '${item.totalPriceLimit}',
                            style: TextStyle(
                              fontSize: 20.px,
                              fontWeight: FontWeight.bold,
                              color: AppColors.startColor,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                      Column(
                        children: [
                          Text(
                            '',
                            style: TextStyle(
                              fontSize: 14.px,
                              fontWeight: FontWeight.bold,
                              color: AppColors.startColor,
                            ),
                            textAlign: TextAlign.end,
                          ),
                          SizedBox(height: 2.px),
                        ],
                      ),
                      SizedBox(width: 10.px),
                      Column(
                        children: [
                          Text(
                            '今日限价',
                            style: TextStyle(
                              fontSize: 12.px,
                              color: AppColors.backgroundColorGrey,
                            ),
                            textAlign: TextAlign.end,
                          ),
                          SizedBox(height: 4.px),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          if (item.incubationStatus == 'COMPLETE')
            Positioned(
              top: 0,
              right: 0,
              child: SizedBox(
                width: 47.px,
                height: 45.px,
                child: ImageAssetWidget(
                  imageUrl: 'static/images/market/success.png',
                  width: 47.px,
                  height: 45.px,
                ),
              ),
            ),
        ],
      ),
    );
  }
}
